package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func main() {
	engine := gin.Default()
	engine.LoadHTMLGlob("template/*")
	engine.GET("/nomaljson", nomaljson)
	engine.GET("/asciijson", asciijson)
	engine.GET("/index", index)
	engine.POST("/login", login)
	engine.GET("/purejson", purejson)
	engine.GET("securejson", securejson)
	engine.Run()
}

func securejson(c *gin.Context) {
	data := []string{"a", "b", "c"}
	//c.SecureJSON(http.StatusOK, data)
	c.JSON(http.StatusOK, data)
}

func purejson(c *gin.Context) {
	//c.JSON(http.StatusOK, gin.H{"html": "<b>hello world</b>"})
	c.PureJSON(http.StatusOK, gin.H{"html": "<b>hello world</b>"})
}

func login(c *gin.Context) {
	var loginForm LoginForm
	if c.ShouldBind(&loginForm) == nil {
		if loginForm.Username == "root" && loginForm.Password == "root" {
			c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "login success"})
		} else {
			c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "login failed"})
		}
	}
}

type LoginForm struct {
	Username string `form:"username" binding:"required"`
	Password string `form:"password" binding:"required"`
}

func index(c *gin.Context) {
	data := make(map[string]string)
	data["title"] = "gin入门"
	data["date"] = time.Now().Format("2006-01-02 15:04:05.000")
	c.HTML(http.StatusOK, "index.tmpl", data)
}

func nomaljson(context *gin.Context) {
	data := make(map[string]string)
	data["hello"] = "你好"
	data["world"] = "<br/>"
	context.JSON(http.StatusOK, data)
}
func asciijson(context *gin.Context) {
	data := make(map[string]interface{})
	data["hello"] = "你好"
	data["world"] = "<br/>"
	context.AsciiJSON(http.StatusOK, data)
}
